package org.apache.poi.xslf.usermodel;

import io.gitee.jinceon.core.DataSource;
import io.gitee.jinceon.core.model.Text;
import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;

import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class TextHelper {
    /**
     * 直接将textShape的文本清除掉，并更新为text
     * 样式采用第一个paragraph下的第一个textrun的。
     * @param textShape
     * @param text
     */
    public static void setText(XSLFTextShape textShape, String text){
        List<XSLFTextParagraph> paragraphs = textShape.getTextParagraphs();
        if (paragraphs.isEmpty()) {
            textShape.setText(text);
        }else{
            int size = paragraphs.size();
            for(int i=size;i>1;i--){
                textShape.removeTextParagraph(paragraphs.get(i-1));
            }
            XSLFTextParagraph paragraph = paragraphs.get(0);
            List<XSLFTextRun> textRuns = paragraph.getTextRuns();
            int textRunSize = textRuns.size();
            if(textRunSize > 1) {
                for (int i = textRunSize; i > 1; i--) {
                    paragraph.removeTextRun(textRuns.get(i - 1));
                }
             //   textRuns.get(0).setText(text);
                XSLFTextRun run = textRuns.get(0);
              /*  System.out.println("text->"+run.getRawText()+",fontfamiliy:"+run.getFontFamily() + "fontSize:"+ run.getFontSize()
                 +"fontcolor" + run.getFontColor());*/
                run.setText(text);
            }else {
                if(textRunSize == 1) {
                    XSLFTextRun run = textRuns.get(0);
                    run.setText(text);
                } else {
                    XSLFTextRun run = paragraph.addNewTextRun();
                    run.setText(text);
                    run.setFontFamily("微软雅黑");
                    run.setFontSize(9.0);
                    run.setBold(false);
                    run.setFontColor(Color.BLACK);
                }
             //   textShape.setText(text);
            }
        }
    }

    public static void renderText(XSLFTextShape textShape, DataSource dataSource){
        String shapeSpel = ShapeHelper.getAlternativeText(textShape);
        Object rootObject = null;
        SpelExpressionParser parser = new SpelExpressionParser();
        if(shapeSpel.contains("#")){
            // #user，把 #user 作为 rootObject
            rootObject = parser.parseExpression(shapeSpel).getValue(dataSource.getEvaluationContext());
        }
        List<XSLFTextParagraph> paragraphs = textShape.getTextParagraphs();
        for (XSLFTextParagraph paragraph : paragraphs) {
            List<XSLFTextRun> portions = paragraph.getTextRuns();
            XSLFTextRun complete = null;
            StringBuilder completeText = new StringBuilder();
            List<XSLFTextRun> temp = new ArrayList<>();
            for (XSLFTextRun portion : portions) {
                String spel = portion.getRawText();
                log.debug("spel: {}", spel);
                if(spel.contains("#{") && spel.contains("}")){
                    complete = portion;
                    completeText.append(portion.getRawText());
                }else if(spel.contains("#{")){
                    complete = portion;
                    completeText.append(portion.getRawText());
                    continue;
                }else if(complete != null && spel.contains("}")){
                    complete.setText(complete.getRawText() + portion.getRawText());
                    completeText.append(portion.getRawText());
                    temp.add(portion);
                }else if(complete != null){
                    completeText.append(portion.getRawText());
                    temp.add(portion);
                    continue;
                }else{
                    continue;
                }
                for(XSLFTextRun t:temp){
                    t.setText("");
                }
                Object text = parser.parseExpression(completeText.toString(), new TemplateParserContext()).getValue(dataSource.getEvaluationContext(), rootObject);
                log.debug("spel: {}, text: {}", completeText, text);
                if(text instanceof Text){
                    Text txt = (Text)text;
                    complete.setText(txt.getText());
                    if(txt.getCustomizeFunction() != null){
                        txt.getCustomizeFunction().accept(complete);
                    }
                }else{
                    complete.setText(String.valueOf(text));
                }
                complete = null;
                completeText.delete(0, completeText.length());
            }
        }
    }


    public static String escapeSpecialCharacters(String input) {
        // 使用正则表达式替换所有特殊字符
        return input.replaceAll("([\\*\\(\\)\\?\\+\\.\\[\\]\\{\\}\\|\\\\\\^\\$])", "\\\\$1");
    }

    /**
     * 处理文字内容
     * @param textShape
     * @param keyName
     * @param keyValue
     * @param prefix
     * @param suffix
     */
    public static void renderText(XSLFTextShape textShape, String keyName, String keyValue, String prefix, String suffix){
        List<XSLFTextParagraph> paragraphs = textShape.getTextParagraphs();
        String placeholderPattern = escapeSpecialCharacters(prefix) + "(.*?)" + escapeSpecialCharacters(suffix);
        Pattern pattern = Pattern.compile(placeholderPattern);
        for (XSLFTextParagraph paragraph : paragraphs) {
            List<XSLFTextRun> portions = paragraph.getTextRuns();
            XSLFTextRun complete = null;
            StringBuilder completeText = new StringBuilder();
            List<XSLFTextRun> temp = new ArrayList<>();
            List<XSLFTextRun> state = new ArrayList<>();
            for (XSLFTextRun portion : portions) {
                String spel = portion.getRawText();
                // 使用正则表达式查找占位符
                Matcher matcher = pattern.matcher(spel);
                log.debug("spel: {}", spel);

                if (matcher.find()) {
                    complete = portion;
                    completeText.append(portion.getRawText());
                }else if(complete== null && spel.contains(prefix)){
                    complete = portion;
                    completeText.append(portion.getRawText());
                    continue;
                }else if(complete != null && spel.contains(suffix)){
                    completeText.append(portion.getRawText());
                    String complate = completeText.toString();
                    if (complate.contains(keyName)) {
                        temp.add(portion);
                        complete.setText(complete.getRawText() + portion.getRawText());
                        if(!isAllChinese(complate)){
                            temp.addAll(state);
                        }
                    }
                }else if(complete != null){
                    completeText.append(portion.getRawText());
                    String complate = completeText.toString();
                    state.add(portion);
                    if (complate.contains(keyName)) {
                       temp.add(portion);
                    }
                    continue;
                }else{
                    continue;
                }
                for(XSLFTextRun t:temp){
                    t.setText("");
                }
                log.debug("spel: {}, text: {}", completeText, keyValue);
                String complate = completeText.toString();
                if (complate.contains(keyName)) {
                    complete.setText(String.valueOf(keyValue));
                }
                complete = null;
                completeText.delete(0, completeText.length());
            }
        }
    }

    private static boolean isAllChinese(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        // 匹配所有字符是否都在汉字 Unicode 范围内
        return str.matches("[\\u4e00-\\u9fa5]+");
    }
}
